package com.example.security.config;

import com.example.security.entity.bo.UserDetailsImpl;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.AuditorAware;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Optional;

/**
 * 自动注入创建人和修改人
 *
 * @author novel
 * @date 2020/11/4
 */
@Configuration
public class BaseEntityAuditor implements AuditorAware<String> {
    @Override
    public Optional<String> getCurrentAuditor() {
        if (getLoginUser() != null) {
            return Optional.ofNullable(getLoginUser().getUsername());
        } else {
            return Optional.of("");
        }
    }

    /**
     * 获取当前用户
     *
     * @return 取不到返回 new User()
     */
    public static UserDetailsImpl getLoginUser() {
        try {
            Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            if (principal != null) {
                return (UserDetailsImpl) principal;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        // 如果没有登录，则返回实例化空的User对象。
        return null;
    }
}
